# coding:utf-8
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from book import models
from book.serializer import BookModelSerializer


class BookGenericAPIView(GenericAPIView):
    queryset = models.Book.objects.filter(is_delete=False).all()
    serializer_class = BookModelSerializer

    def get(self, request, *args, **kwargs):
        if kwargs.get('pk', None):
            book = self.get_object()
            book_ser = self.get_serializer(book)
            return Response(book_ser.data)
        else:
            book_list = self.get_queryset()
            book_ser = self.get_serializer(book_list, many=True)
            return Response(book_ser.data)

    def post(self, request, *args, **kwargs):
        if isinstance(request.data, dict):
            book_ser = self.get_serializer(data=request.data)
            book_ser.is_valid(raise_exception=True)
            book_ser.save()
            return Response(data=book_ser.data)
        elif isinstance(request.data, list):
            # 现在book_ser是ListSerializer对象
            book_ser = self.get_serializer(data=request.data, many=True)
            book_ser.is_valid(raise_exception=True)
            book_ser.save()
            return Response(data=book_ser.data)

    def put(self, request, *args, **kwargs):
        if kwargs.get('pk', None):
            book = self.get_object()
            # partial = True修改局部
            book_ser = self.get_serializer(instance=book, data=request.data, partial=True)
            book_ser.is_valid(raise_exception=True)
            book_ser.save()
            return Response(data=book_ser.data)

        else:
            # 批量修改
            book_list = []
            modify_data = []

            # 处理传入的数据，对象列表[book1，book2]，修改的数据列表[{name:xx,price:xx},{name:xx,price:xx}]
            for item in request.data:
                pk = item.pop('id')
                book = models.Book.objects.get(pk=pk)
                book_list.append(book)
                modify_data.append(item)

            # 方式1，for循环一个一个修改
            # for i, si_data in enumerate(modify_data):
            #     book_ser = self.get_serializer(instance=book_list[i], data=si_data)
            #     book_ser.is_valid(raise_exception=True)
            #     book_ser.save()
            # return Response(data='ok')

            # 方式2，在serializer中写一个类，继承ListSerializer，重写update方法，在序列化中关联list_serializer_class=BookListSerializer
            book_ser = self.get_serializer(instance=book_list, data=modify_data, many=True)
            book_ser.is_valid(raise_exception=True)
            book_ser.save()
            return Response(data=book_ser.data)

    def delete(self, request, *args, **kwargs):
        pks = []
        pk = kwargs.get('pk')
        if pk:
            pks.append(pk)
        else:
            pks = request.data.get('pks')
        ret = models.Book.objects.filter(pk__in=pks, is_delete=False).update(is_delete=True)
        if ret:
            return Response(data={'msg': '成功删除%s条数据' % ret})
        else:
            return Response(data={'msg': '该数据不存在'})
